﻿using System;
using System.IO;
using System.Linq;
using System.Security.Cryptography;
using System.Text;

namespace System
{
    public class EncryptHelper
    {
        #region 加解密

        const string Key = "rew@#$f43r43%#43123s";
        const string IV = "e74@#43454..-+234$#fds";

        public static string Encrypt(string originStr, string key = Key)
        {
            try
            {
                using (AesCryptoServiceProvider aes = new AesCryptoServiceProvider())
                {
                    //aes的key和iv有长度要求
                    aes.Key = Encoding.Unicode.GetBytes(key).Take(32).ToArray();
                    aes.IV = Encoding.Unicode.GetBytes(IV).Take(16).ToArray();
                    var enc = aes.CreateEncryptor(aes.Key, aes.IV);
                    using (MemoryStream ms = new MemoryStream())
                    {
                        using (CryptoStream cs = new CryptoStream(ms, enc, CryptoStreamMode.Write))
                        {
                            var bts = Encoding.Unicode.GetBytes(originStr);
                            cs.Write(bts, 0, bts.Length);
                        }
                        //用Base64编码存储加密后的字符串；其他编码格式可能因不可显示字符而造成数据丢失
                        return Convert.ToBase64String(ms.ToArray());
                    }
                }
            }
            catch (Exception ex)
            {


            }
            return originStr;
        }

        public static string Decrypt(string encryptedStr, string key = Key)
        {
            try
            {
                using (AesCryptoServiceProvider aes = new AesCryptoServiceProvider())
                {
                    aes.Key = Encoding.Unicode.GetBytes(key).Take(32).ToArray();
                    aes.IV = Encoding.Unicode.GetBytes(IV).Take(16).ToArray();
                    var enc = aes.CreateDecryptor(aes.Key, aes.IV);
                    using (MemoryStream ms = new MemoryStream())
                    {
                        using (CryptoStream cs = new CryptoStream(ms, enc, CryptoStreamMode.Write))
                        {
                            var bts = Convert.FromBase64String(encryptedStr);
                            cs.Write(bts, 0, bts.Length);
                        }
                        return Encoding.Unicode.GetString(ms.ToArray());
                    }
                }
            }
            catch (Exception ex)
            {
            }
            return encryptedStr;
        }
        #endregion
    }
}
